#!/bin/bash
# Start Prometheus + Grafana monitoring stack for TT-Metal telemetry
#
# Usage:
#   ./start-monitoring.sh [HOST:PORT] [HOST:PORT] ...
#
# Examples:
#   # Scrape localhost TT-Metal telemetry (default)
#   ./start-monitoring.sh
#
#   # Scrape remote TT-Metal telemetry
#   ./start-monitoring.sh sjc-wh-05:53494
#
#   # Scrape multiple hosts
#   ./start-monitoring.sh sjc-wh-05:53494 sjc-wh-06:53494

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Parse command-line arguments for target hosts
TARGETS=("$@")

# Show help if requested
if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]; then
    grep "^#" "$0" | tail -n +2 | cut -c 3-
    exit 0
fi

# Default: scrape localhost telemetry if no targets specified
if [ ${#TARGETS[@]} -eq 0 ]; then
    TARGETS=("host.docker.internal:8080")
fi

# Resolve hostnames to IPs (for Docker on macOS compatibility)
resolve_target() {
    local target="$1"
    local host="${target%:*}"
    local port="${target##*:}"

    # If it's already an IP address, return as-is
    if [[ "$host" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        echo "$target"
        return
    fi

    # Special case: host.docker.internal doesn't need resolution
    if [[ "$host" == "host.docker.internal" ]]; then
        echo "$target"
        return
    fi

    # Try to resolve hostname to IPv4
    local resolved_ip

    # Method 1: getent (Linux)
    if command -v getent &>/dev/null; then
        resolved_ip=$(getent hosts "$host" 2>/dev/null | awk '{print $1; exit}')
    fi

    # Method 2: dscacheutil (macOS)
    if [[ -z "$resolved_ip" ]] && command -v dscacheutil &>/dev/null; then
        resolved_ip=$(dscacheutil -q host -a name "$host" 2>/dev/null | awk '/^ip_address:/ {print $2; exit}')
    fi

    # Method 3: host command
    if [[ -z "$resolved_ip" ]] && command -v host &>/dev/null; then
        resolved_ip=$(host -t A "$host" 2>/dev/null | awk '/has address/ {print $NF; exit}')
    fi

    # Method 4: nslookup
    if [[ -z "$resolved_ip" ]] && command -v nslookup &>/dev/null; then
        resolved_ip=$(nslookup "$host" 2>/dev/null | awk '/^Address: / && !/127\.0\.0\.1/ {print $2; exit}')
    fi

    # If resolved successfully, return IP:port
    if [[ -n "$resolved_ip" ]]; then
        echo "  Resolved $host -> $resolved_ip" >&2
        echo "$resolved_ip:$port"
    else
        echo "  Warning: Could not resolve $host, using as-is" >&2
        echo "$target"
    fi
}

# Deduplicate and resolve targets
UNIQUE_TARGETS=()
for target in "${TARGETS[@]}"; do
    # Check if target is already in UNIQUE_TARGETS
    found=0
    for unique in "${UNIQUE_TARGETS[@]}"; do
        if [[ "$unique" == "$target" ]]; then
            found=1
            break
        fi
    done
    # Add if not found
    if [[ $found -eq 0 ]]; then
        resolved_target=$(resolve_target "$target")
        UNIQUE_TARGETS+=("$resolved_target")
    fi
done
TARGETS=("${UNIQUE_TARGETS[@]}")

# Generate prometheus.yml with targets
generate_prometheus_config() {
    cat > prometheus.yml <<EOF
# Prometheus configuration file for scraping TT-Metal telemetry metrics
#
# AUTO-GENERATED by start-monitoring.sh - Do not edit manually!
# To update targets, run: ./start-monitoring.sh HOST:PORT [HOST:PORT ...]

global:
  scrape_interval: 15s     # Scrape targets every 15 seconds
  evaluation_interval: 15s # Evaluate rules every 15 seconds

scrape_configs:
  - job_name: 'tt-telemetry'
    metrics_path: '/api/metrics'
    static_configs:
EOF

    # Create separate target block for each host
    for i in "${!TARGETS[@]}"; do
        local target="${TARGETS[$i]}"
        cat >> prometheus.yml <<EOF
      - targets: ['${target}']
EOF
    done

}

echo "==================================================================="
echo "TT-Metal Telemetry Monitoring Stack"
echo "==================================================================="
echo ""
echo "TT-Metal Telemetry endpoints:"
# Print original targets (before resolution) from command line args
for target in "$@"; do
    [[ -n "$target" ]] && echo "  - http://$target/api/metrics"
done

echo ""
echo "Generating Prometheus configuration..."
generate_prometheus_config

# Detect docker compose vs docker-compose
if docker compose version &>/dev/null; then
    DOCKER_COMPOSE="docker compose"
elif docker-compose version &>/dev/null; then
    DOCKER_COMPOSE="docker-compose"
else
    echo "Error: Neither 'docker compose' nor 'docker-compose' found"
    exit 1
fi

echo "Starting Docker containers..."
$DOCKER_COMPOSE down 2>/dev/null || true
$DOCKER_COMPOSE up -d

echo ""
echo "==================================================================="
echo "Monitoring stack is running!"
echo "==================================================================="
echo ""
echo "Access points:"
echo "  Prometheus: http://localhost:9090"
echo "  Grafana:    http://localhost:3000 (admin/admin)"
echo ""
echo "To stop the monitoring stack:"
echo "  $DOCKER_COMPOSE down"
echo ""
echo "To view logs:"
echo "  $DOCKER_COMPOSE logs -f"
echo "==================================================================="
